<script setup lang="ts">
import Write from './Writeed.vue'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { ref, unref, inject, Ref } from 'vue'
import { modifyApi } from '@/api/franchiser'
import { ElMessage } from 'element-plus'
import { Row } from '@/api/franchiser'
const emit = defineEmits(['close', 'get-list'])
const currentRow: Ref<Row> = inject('currentRow') as Ref<Row>
const writeRef = ref<ComponentRef<typeof Write>>()

const loading = ref(false)
function compareObjects(new_obj, old_obj) {
  const result = {}
  for (const key in new_obj) {
    if (old_obj.hasOwnProperty(key)) {
      if (new_obj[key] !== old_obj[key]) {
        result[key] = new_obj[key]
      }
    }
  }
  return result
}

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  const list = compareObjects(formData, currentRow._rawValue)
  if (formData.password) {
    list.password = formData.password
  }
  if (Object.keys(list).length == 0) {
    ElMessage.error('未修改任何数据，无需提交')
    return
  }
  const parm = {
    ...list,
    id: formData.id
  }
  if (parm) {
    loading.value = true
    const res = await modifyApi(parm)
      .catch(() => {})
      .finally(() => {
        loading.value = false
      })
    if (res) {
      ElMessage.success(res.msg)
      write?.reset()
      emit('close')
      emit('get-list')
    }
  }
}
</script>

<template>
  <ContentDetailWrap title="客户编辑">
    <Write ref="writeRef" />

    <template #footer>
      <div class="w-full flex items-center justify-center">
        <BaseButton type="primary" :loading="loading" @click="save">保存</BaseButton>
        <BaseButton @click="emit('close')">取消</BaseButton>
      </div>
    </template>
  </ContentDetailWrap>
</template>
